package com.laf.mall.api.rest;

import com.laf.mall.api.dto.Member;
import com.laf.mall.api.dto.MemberCar;
import com.laf.mall.api.dto.ParkingRule;
import com.laf.mall.api.dto.PointsDeduction;
import com.laf.mall.api.rest.dto.PointsConsumeDto;
import com.laf.mall.api.rest.dto.PointsFreezeDto;
import com.laf.mall.api.service.MemberCarService;
import com.laf.mall.api.service.MemberService;
import com.laf.mall.api.service.ParkingRuleService;
import com.laf.mall.api.service.PointsDeductionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author ygl
 * @create 2018-12-28
 * @DESCRIPTION
 * 会员停车的接口
 **/
@RestController
@RequestMapping("/member/parking")
public class MemberParkingRest {

    @Autowired
    private MemberCarService memberCarService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ParkingRuleService parkingRuleService;

    @Autowired
    private PointsDeductionService pointsDeductionService;

    private final String signKey = "ZJGC";

    /**
     * 积分冻结
     * @return
     */
    @PostMapping("/points/freeze")
    private Map<String,Object> freezePoints(@RequestBody PointsFreezeDto model){
        Map<String,Object> result = new HashMap<>();
        String carNumer = model.getCarNumer();
        Double totalCost = model.getTotalCost();
        Long submitTime = model.getSubmitTime();
        String strToSign = carNumer+totalCost+submitTime+signKey;
        String signStr = DigestUtils.md5DigestAsHex(strToSign.getBytes()).toUpperCase();
        if (!signStr.equals(model.getSignStr())) {
            result.put("offsetResult","fail");
            result.put("message","签名错误！");
            return result;
        }
        List<MemberCar> memberCarList = memberCarService.findByCarNumber(carNumer);
        if (CollectionUtils.isEmpty(memberCarList)) {
            result.put("offsetResult","success");
            result.put("message","该车牌未被绑定!");
            result.put("carNumer",carNumer);
            result.put("offsetNumber","-1");
            result.put("offsetCost",0);
            return result;
        }
        if (memberCarList.size() != 1) {
            result.put("offsetResult","success");
            result.put("message","多个会员绑定了该车牌!");
            result.put("carNumer",carNumer);
            result.put("offsetNumber","-1");
            result.put("offsetCost",0);
            return result;
        }
        MemberCar memberCar = memberCarList.get(0);
        int memberId = memberCar.getMemberId();
        // 查询积分抵扣规则
        ParkingRule parkingRule = parkingRuleService.findOne();
        if (parkingRule == null) {
            result.put("offsetResult","success");
            result.put("message","未设置积分抵扣规则!");
            result.put("carNumer",carNumer);
            result.put("offsetNumber","-1");
            result.put("offsetCost",0);
            return result;
        }
        Member member = memberService.getSimpleMemberById(memberId);
        // 获取会员的可用积分
        int usable_points = member.getUsable_points();
        /**
         * 计算抵扣了多少金额：
         */
        Integer pointsPerYuan = parkingRule.getPointsPerYuan();
        Integer mostYuan = parkingRule.getMostYuan();
        // 可以抵扣多少金额
        int money = usable_points / pointsPerYuan;
        if(money == 0){
            result.put("offsetResult","success");
            result.put("carNumer",carNumer);
            result.put("offsetNumber","-1");
            result.put("offsetCost",0);
            return result;
        }
        // 如果大于每天最多可以抵扣的金额：那么抵扣的金额就是最大可以抵扣金额
        if(money > mostYuan){
            money = mostYuan;
        }
        // 会员 扣除账户中的积分
        member.setUsable_points(usable_points - money*pointsPerYuan);
        memberService.updatePoints(member.getMember_id(),member.getCumulate_points(),member.getUsable_points());
        // 生成扣款记录
        PointsDeduction deduction = new PointsDeduction();
        deduction.setOffsetNumber(UUID.randomUUID().toString());


        deduction.setMemberId(memberId);
        deduction.setCarNumber(carNumer);
        deduction.setTotalCost(totalCost);
        deduction.setDeductionCost(money);
        deduction.setDeductionPoints(money * pointsPerYuan);
        deduction.setStatus(1);
        deduction.setFrozenDate(new Date());
        pointsDeductionService.insert(deduction);
        // 返回数据
        result.put("offsetResult","success");
        result.put("carNumer",carNumer);
        result.put("offsetNumber",deduction.getOffsetNumber());
        result.put("offsetCost",money);
        return result;
    }


    @PostMapping("/points/consume")
    private Map<String,Object> consumePoints(@RequestBody PointsConsumeDto model){
        Map<String,Object> result = new HashMap<>();
        String offsetNumber = model.getOffsetNumber();
        if ("-1".equals(offsetNumber)) {
            result.put("offsetResult","success");
            result.put("offsetNumber",offsetNumber);
            return result;
        }
        Long submitTime = model.getSubmitTime();
        String strToSign = offsetNumber+submitTime+signKey;
        String signStr = DigestUtils.md5DigestAsHex(strToSign.getBytes()).toUpperCase();
        if (!signStr.equals(model.getSignStr())) {
            result.put("offsetResult","fail");
            result.put("message","签名错误！");
            return result;
        }
        boolean flag = false;
        List<PointsDeduction> pointsDeductionList = pointsDeductionService.findByOffsetNumber(offsetNumber);
        for (PointsDeduction deduction : pointsDeductionList) {
            // 冻结的数据
            if (deduction.getStatus() == 1) {
                deduction.setStatus(2);
                deduction.setBizDate(new Date());
                pointsDeductionService.updateStatus(deduction);
                flag = true;
            }
        }
        if(flag){
            result.put("offsetResult","success");
            result.put("offsetNumber",offsetNumber);
            return result;
        }else{
            result.put("offsetResult","fail");
            result.put("message","抵扣失败！");
            result.put("offsetNumber",offsetNumber);
            return result;
        }
    }


}
